<?php

require FCPATH . 'application/controllers/frontend.php';

class Project extends Frontend {

    public function __construct() {
        parent::__construct();

        $this->load->model('project_model', 'model');
    }

    public function find() {
        $id = intval($this->uri->segment(3));

        $project = $this->model->find($id);

        if (!$project) {
            $this->json_back('XT002', '该项目已被删除,请刷新本页');
        }
        
        if ($this->input->cookie('lang') == 'en') {
            $project->title = $project->title_en;
            $project->content = $project->content_en;
        }
        unset($project->title_en, $project->content_en);

        $data = array(
            'project' => $project
        );
        
        if ($data['project']->album > 0) {
            $this->load->model('photo_model');
            $data['photos'] = $this->photo_model->records(0, 0, array(array('album', $data['project']->album)));
        }

        $this->json_back('XT001', '', $data);
    }

    public function records() {
        $title = trim($this->input->get('title'));
        $type = intval($this->input->get('type'));
        $year = intval($this->input->get('year'));
        $area = intval($this->input->get('area'));
        $page = intval($this->input->get('page'));
        $page = $page <= 0 ? 1 : $page;
        $page_size = intval($this->input->get('pageSize'));
        $offset = $page_size * ($page - 1);
	$page_size = $page_size <= 0 ? 10 : $page_size;

        $conditions = array();

        if(!empty($title)){
            if($this->input->cookie('lang')=='en'){
                $conditions[] = array('title_en like','%'.$title.'%');
            }else{
                $conditions[] = array('title like','%'.$title.'%');
            }
        }
        
        if ($type) {
            $conditions[] = array('type', $type);
        }

        if ($year) {
	    if($year < 2007){
		$conditions[] = array('year <=', '2007');
	    }else{
		$conditions[] = array('year', $year);
	    }
        }

        if ($area) {
            $conditions[] = array('area', $area);
        }
        
        $records = $this->model->records($page_size, $offset, $conditions);
        
        foreach ($records as &$record) {
            if ($this->input->cookie('lang') == 'en') {
                $record->title = $record->title_en;
                $record->content = $record->content_en;
            }
            unset($record->title_en, $record->content_en);
        }

        $this->json_back('XT001', '', array(
            'total' => $this->model->total($conditions),
            'records' => $records
        ));
    }

}
